﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

namespace Mammoth.Libs
{

    public abstract class WPFViewModelBase : INotifyPropertyChanged, INotifyDataErrorInfo
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;

        public IInputElement Dispatcher { get; set; }

        private IDictionary<string, string> errors;

        public WPFViewModelBase(IInputElement dispatcher)
        {
            Dispatcher = dispatcher;
            errors = new Dictionary<string, string>();
        }

        public void RaiseEvent(RoutedEventArgs e)
        {
            var msg = string.Format("*** Dispatcher for '{0}' is not registered", this.GetType().ToString());
            Debug.WriteLineIf(Dispatcher == null, msg);
            if(Dispatcher != null)
                Dispatcher.RaiseEvent(e);
        }

        protected void AddHandler(RoutedEvent routedEvent, Delegate handler)
        {
            if (Dispatcher != null)
                Dispatcher.AddHandler(routedEvent, handler);
        }

        protected void RemoveHandler(RoutedEvent routedEvent, Delegate handler)
        {
            if (Dispatcher != null)
                Dispatcher.RemoveHandler(routedEvent, handler);
        }

        public IEnumerable GetErrors(string propertyName)
        {
            string result;
            if(errors.TryGetValue(propertyName, out result))
            {
                return new string[] { result };
            }
            return null;
        }

        public bool HasErrors
        {
            get { return errors.Count() > 0; }
        }

        protected void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        protected void OnErrorsChanged(string propertyName)
        {
            if (ErrorsChanged != null)
            {
                ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
            }
        }
    }
}
